package cn.jdemo.juc.cyclicBarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @date 2020/12/7
 */
public class DemoCyclicBarrier {

    public static void main(String[] args) {
        test01(args);
    }

    /**
     * 执行结果如下:
     * 10
     * 11
     * 12
     * 13
     * 14
     * 线程累积5个后应该会执行...
     * 15
     * 16
     * 17
     * 18
     * 19
     * 线程累积5个后应该会执行...
     *
     * @param args
     */
    public static void test01(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, ()->{
            System.out.println("线程累积5个后应该会执行...");
        });

        for (int i=0;i<8;i++){
            new Thread(()->{
                // System.out.println(temp.getAndIncrement());
                try {
                    System.out.println("prepare : "+Thread.currentThread().getName());
                    cyclicBarrier.await();
                    System.out.println("after : "+Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
